package com.xvyy.tingshu.search.listener;

import com.xvyy.tingshu.search.service.impl.ItemServiceImpl;
import org.redisson.api.RBloomFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplicationRunListener;
import org.springframework.context.ConfigurableApplicationContext;

import java.time.Duration;
import java.util.List;

/**
 * ClassName: DistributedBloomFilterListener
 * Package: com.xvyy.tingshu.search.listener
 *
 * @Description: 分布式布隆过滤器监听器
 * @Author: xvyy
 * @Create: 2025/2/7 - 15:02
 * @Version: v1.0
 */
//@Component 无需加@Component注解，扫描不到，使用SPI机制自动加载
public class DistributedBloomFilterListener implements SpringApplicationRunListener {

    Logger logger = LoggerFactory.getLogger(DistributedBloomFilterListener.class);

    @Override
    public void started(ConfigurableApplicationContext context, Duration timeTaken) {
        logger.info("通过SpringBoot监听器，初始化分布式布隆过滤器开始...");

        boolean containsBean = context.containsBean("rBloomFilter");
        // 1. 判断是否存在布隆过滤器对象
        if (containsBean) {
            // 2 存在，获取布隆过滤器对象
            RBloomFilter rBloomFilter = context.getBean("rBloomFilter", RBloomFilter.class);
            // 3. 判断布隆过滤器中是否有数据，如果没有数据，则初始化布隆过滤器
            long count = rBloomFilter.count();
            if (count == 0) {
                // 4. 从MySQL中找到数据库中所有的albumIdList
                ItemServiceImpl itemService = context.getBean("itemServiceImpl", ItemServiceImpl.class);
                List<Long> albumInfoIdList = itemService.getAlbumInfoIdList();
                // 5. 将albumIdList添加到RBloomFilter中
                for (Long albumInfoId : albumInfoIdList) {
                    rBloomFilter.add(albumInfoId);
                }
                logger.info("通过SpringBoot监听器，初始化分布式布隆过滤器完成…初始化数据量：{}", rBloomFilter.count());
            }
        }
    }

}
